var express = require('express');
var router = express.Router();
const mongodb= require('../components/mongo');

const multer = require('multer');
const storage = multer.memoryStorage();
const uploader = multer({storage:storage});
const fs = require('fs');
const hostIP = require('../components/host').HOST;


router.get('/',function(req, res, next) {
   res.render('registSample',{title:'RegistSample'});
}).post('/',async function(req, res) {
   console.log(req.body);
	var m_uid = req.body.u_id;
	var m_password = req.body.password;
	const result = await mongodb.find("User",{u_id:m_uid});
	console.log(result);
	if(result.length > 0){
	res.json({errno:0,errmsg:"",data:{res:false}});
	}else{
		const local = "public/";
		const user_storage_path = "storage/users/";


		var dirPath = local + user_storage_path + m_uid;
		
		var exsist = fs.existsSync(dirPath)
		if(!exsist){
			fs.mkdirSync(dirPath);		
		}

		var pre_insert = {
		   u_id:m_uid,
		   name:'',
		   password:m_password,
		   email:'',
		   phone:'',
		   hobby:'',
		   content:'',
		   head_image:hostIP +'storage/' +'defaultAvatar.jpg',
		}
		const insert_result = await mongodb.insert("User",pre_insert);
		res.json({
		   errno:0,
		   errmsg:"",
		   data:{res:true},
		   });
	}
});


// var m_uid = req.body.u_id;
//    var m_name = req.body.name;
//    var m_password = req.body.password;
//    var m_email = req.body.email;
//    var m_phone = req.body.phone;
//    var m_hobby = req.body.hobby;
//    var m_content = req.body.content;
//    const result = await mongodb.find("User",{u_id:m_uid});
//    console.log(result);
//    if(result.length > 0){
// 	   res.json({errno:0,errmsg:"",data:{res:false}});
//    }else{
// 	   const local = "public/";
// 	   const user_storage_path = "storage/users/";
	   
// 	   var fileFormat = (req.file.originalname).split(".");
// 	   var filename = req.file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1];
	   
// 	   var dirPath = local + user_storage_path + m_uid;
// 	   var filePath = dirPath + '/' + filename;
	   
// 	   fs.mkdirSync(dirPath);
// 	   fs.writeFileSync(filePath,req.file.buffer);
// 	   var pre_insert = {
// 		   u_id:m_uid,
// 		   name:,
// 		   password:m_password,
// 		   email:m_email,
// 		   phone:m_phone,
// 		   hobby:m_hobby,
// 		   content:m_content,
// 		   head_image:hostIP+user_storage_path+ m_uid + '/' + filename,
// 	   }
// 	   const insert_result = await mongodb.insert("User",pre_insert);
// 	   res.json({
// 		   errno:0,
// 		   errmsg:"",
// 		   data:{res:true},
// 		   });
//    }

module.exports = router;